package com.stone.gateway.config;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.HttpRequest;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.boot.web.embedded.netty.NettyReactiveWebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.stereotype.Component;
import reactor.netty.ConnectionObserver;
import reactor.netty.NettyPipeline;

/**
 * @author fxj
 * date 2021-10-08
 */

@Component
@ConditionalOnExpression("${ctj.gateway.enableSpecialChar:false}")
public class FixSpecialChar implements WebServerFactoryCustomizer<NettyReactiveWebServerFactory> {

    @Override
    public void customize(NettyReactiveWebServerFactory factory) {
        factory.addServerCustomizers(httpServer ->
                httpServer.observe((conn, state) -> {
                    if (state == ConnectionObserver.State.CONNECTED) {
                        conn.channel().pipeline().addAfter(NettyPipeline.HttpCodec, "", new QueryHandler());
                    }
                }));
    }


    class QueryHandler extends ChannelInboundHandlerAdapter {

        public QueryHandler() {
        }

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) {
            if (msg instanceof HttpRequest) {
                HttpRequest request = (HttpRequest) msg;
                String url = request.uri();
                // todo fix url
                String fixUrl = url.replace("{", "%7B")
                        .replace("}", "%7D")
                        .replace("\"","%22")
                        .replace("<","%0A%3C")
                        .replace(">","%0A%3E")
                        .replace("[","%0A%5B")
                        .replace("]","%0A%5D")
                        .replace("^","%0A%5E")
                        .replace("|","%0A%7C")
                        .replace("\\","%0A%5C")
                        .replace("`","%0A%0A%60");
                request.setUri(fixUrl);
            }
            ctx.fireChannelRead(msg);
        }
    }
}